/*
 *  Copyright (C) 2010 Glauco
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.balisunrise.dao.hibernate;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import org.balisunrise.application.Application;
import org.balisunrise.common.DAO;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

/**
 * Hibernate Utility class with a convenient method to get Session Factory object.
 *
 * @author Glauco
 */
public class HibernateUtil {
    private static final AnnotationConfiguration cfg;
    private static SessionFactory sessionFactory;
    private static HDAO DAO;

    static {
        try {

            File file = new File("./hibernate.cfg.xml");
            if (file.exists()){

                String msg = "Configurações carregadas de \"hibernate.cfg.xml\"";
                Application.get().getLogger().log(Level.INFO, msg);

                cfg = new AnnotationConfiguration().configure(file);
                buildSessionFactory();

            } else {

                // Load settings from hibernate.properties
                cfg = new AnnotationConfiguration();
                Properties p = new Properties();

                // ... set other configuration options programmatically
                file = new File("./hibernate.properties");

                if (file.exists()){
                    try {

                        p.load(new FileInputStream(file));
                        System.getProperties().putAll(p);

                        String msg = "Configurações carregadas de \"hibernate.properties\"";
                        Application.get().getLogger().log(Level.INFO, msg);

                    } catch (IOException ex) {

                        String msg = "Falha ao carregar configurações do Hibernate.";
                        Application.get().getLogger().log(Level.SEVERE, msg, ex);

                        // não leu arquivo
                        file.delete();
                    }
                } else {

                    String msg = "Configurações padrão do Hibernate foram carregadas.";
                    Application.get().getLogger().log(Level.INFO, msg);

                    p.setProperty("hibernate.connection.driver_class", "org.postgresql.Driver");
                    p.setProperty("hibernate.connection.url", "jdbc:postgresql://localhost:5432/balisunrise");
                    p.setProperty("hibernate.connection.username", "postgres");
                    p.setProperty("hibernate.connection.password", "master");
                    p.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
                    p.setProperty("show_sql", "true");
                    p.setProperty("format_sql", "true");
                    p.setProperty("hibernate.c3p0.max_statements", "100");
                    p.setProperty("hibernate.hbm2ddl.auto", "update");
                    //p.setProperty("", "");

                    try{
                        p.store(new FileOutputStream(file), "Propriedades do Hibernate");
                    }catch(Exception ex){
                        msg = "Não Salvou o arquivo de configurações padrão.";
                        Application.get().getLogger().log(Level.SEVERE, msg, ex);
                    }
                }
                
                cfg.addProperties(p);
                
                buildSessionFactory();
            }
            
        } catch (Throwable ex) {

            String msg = "Initial SessionFactory creation failed." + ex;
            System.err.println(msg);
            Application.get().getLogger().log(Level.SEVERE, msg, ex);

            throw new ExceptionInInitializerError(ex);
        }
        
        DAO = new HDAO();
    }
    
    public static void addAnnotatedClass(Class[] classes){

        if (classes == null)
            return;

        for (int i = 0; i < classes.length; i++) {
            Class c = classes[i];
            cfg.addAnnotatedClass(c);
        }
        
        buildSessionFactory();
    }

    private static void buildSessionFactory(){
        if(sessionFactory != null)
            sessionFactory.close();
        
        sessionFactory = cfg.buildSessionFactory();
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdown() {
        // Close caches and connection pools
        getSessionFactory().close();
    }

    public static DAO<Session> getDAO(){
        return DAO;
    }
}
